import { Response } from 'express';
import { Income } from '@/models/Income';
import { Car } from '@/models/Vehicle';
import { AuthenticatedRequest } from '@/middleware/auth';

/**
 * @swagger
 * /api/incomes:
 *   post:
 *     summary: 创建收入记录
 *     tags: [收入记录]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - vehicleId
 *               - type
 *               - amount
 *               - date
 *             properties:
 *               vehicleId:
 *                 type: string
 *                 description: 车辆ID
 *               type:
 *                 type: string
 *                 description: 收入类型
 *               amount:
 *                 type: number
 *                 description: 收入金额
 *               date:
 *                 type: string
 *                 format: date
 *                 description: 收入日期
 *               description:
 *                 type: string
 *                 description: 描述
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 请求参数错误
 */
export const createIncome = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId, type, amount, date, description } = req.body;
    // 验证车辆是否存在且属于当前用户
    const car = await Car.findOne({
      _id: vehicleId,
      userId: req.userId,
    });
    if (!car) {
      res.status(404).json({ success: false, message: '车辆不存在' });
      return;
    }
    const income = new Income({
      userId: req.userId,
      vehicleId,
      type,
      amount,
      date: new Date(date),
      description,
    });
    await income.save();
    res
      .status(201)
      .json({ success: true, message: '收入记录创建成功', data: income });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/incomes:
 *   get:
 *     summary: 获取收入记录列表
 *     tags: [收入记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: vehicleId
 *         schema:
 *           type: string
 *         description: 车辆ID筛选
 *       - in: query
 *         name: type
 *         schema:
 *           type: string
 *         description: 收入类型筛选
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const getIncomes = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const {
      page = 1,
      limit = 10,
      vehicleId,
      type,
      startDate,
      endDate,
    } = req.query;
    const skip = (Number(page) - 1) * Number(limit);
    const filter: any = { userId: req.userId };
    if (vehicleId) filter.vehicleId = vehicleId;
    if (type) filter.type = type;
    if (startDate || endDate) {
      filter.date = {};
      if (startDate) filter.date.$gte = new Date(startDate as string);
      if (endDate) filter.date.$lte = new Date(endDate as string);
    }
    const incomes = await Income.find(filter)
      .sort({ date: -1 })
      .skip(skip)
      .limit(Number(limit));
    const total = await Income.countDocuments(filter);
    res.status(200).json({
      success: true,
      message: '获取收入记录列表成功',
      data: {
        incomes,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          totalPages: Math.ceil(total / Number(limit)),
        },
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/incomes/{id}:
 *   get:
 *     summary: 获取收入记录详情
 *     tags: [收入记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 收入记录ID
 *     responses:
 *       200:
 *         description: 获取成功
 *       404:
 *         description: 收入记录不存在
 */
export const getIncomeById = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;
    const income = await Income.findOne({ _id: id, userId: req.userId });
    if (!income) {
      res.status(404).json({ success: false, message: '收入记录不存在' });
      return;
    }
    res
      .status(200)
      .json({ success: true, message: '获取收入记录详情成功', data: income });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/incomes/{id}:
 *   put:
 *     summary: 更新收入记录
 *     tags: [收入记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 收入记录ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               type:
 *                 type: string
 *                 description: 收入类型
 *               amount:
 *                 type: number
 *                 description: 收入金额
 *               date:
 *                 type: string
 *                 format: date
 *                 description: 收入日期
 *               description:
 *                 type: string
 *                 description: 描述
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 收入记录不存在
 */
export const updateIncome = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    delete updateData.userId;
    delete updateData.vehicleId;
    if (updateData.date) updateData.date = new Date(updateData.date);
    const income = await Income.findOneAndUpdate(
      { _id: id, userId: req.userId },
      updateData,
      { new: true, runValidators: true }
    );
    if (!income) {
      res.status(404).json({ success: false, message: '收入记录不存在' });
      return;
    }
    res
      .status(200)
      .json({ success: true, message: '更新收入记录成功', data: income });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/incomes/{id}:
 *   delete:
 *     summary: 删除收入记录
 *     tags: [收入记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 收入记录ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 收入记录不存在
 */
export const deleteIncome = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;
    const income = await Income.findOneAndDelete({
      _id: id,
      userId: req.userId,
    });
    if (!income) {
      res.status(404).json({ success: false, message: '收入记录不存在' });
      return;
    }
    res.status(200).json({ success: true, message: '删除收入记录成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};
